<template>
  <div class="app-container">
    <el-card class="box-card">
      <!-- 卡片头-->
      <div slot="header" class="clearfix">
        <span>项目统筹安排</span>
      </div>
      <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="80px">
        <el-form-item label="项目节点" prop="radio1">
          <el-row style="margin-top: 5px">
            <div  style="display: flex;overflow-x: auto" >
              <my_stepbox
                v-for="(item,index) of nodeTypeList"
                :key="index"
                style="cursor: pointer"
                :active="index==nodeActive?false:true"
                :index="item.nodeId"
                :inputValue="item.nodeName"
                @handleClose="abc(index,item)">
              </my_stepbox>
            </div>
          </el-row>
        </el-form-item>
        <el-form-item label="项目周期">
          <el-col :span="11">
            {{zhouQiStart}} ~ {{zhouQiEnd}}
          </el-col>
        </el-form-item>
        <el-form-item label="节点周期">
          {{jieStart}} ~ {{jieEnd}}
        </el-form-item>
        <div v-for="(item,index) of nodeTypeList">
          <table-list v-show="index==nodeActive" :ref="'tab'+index"  :nodeId="item.nodeId" :jieStart="item.jieStart"
                      :jieEnd="item.jieEnd" :tableTimeList="item.tableTimeList"></table-list>
        </div>
        <div style="display: flex;justify-content: center">
          <el-form-item style="margin-top: 30px;display: flex;justify-content: center;margin-left: 0;">
            <el-button :type="saveLoading?'info':'primary'" :loading="saveLoading" @click="submitForm('ruleForm')">立即创建</el-button>
          </el-form-item>
        </div>
      </el-form>

      <el-dialog
            :visible.sync="centerDialogVisible"
            width="30%"
            :show-close="false"
            :close-on-click-modal="false"
            :close-on-press-escape="false"
            center>
        <div style="text-align: center;font-size: 15px;font-weight: bold">请设置项目成员的日志评审人</div>
        <span slot="footer" class="dialog-footer">
        <el-button
            type="primary"
            @click="gotoReview"
            style="width: 135px">去设置
        </el-button>
        </span>
      </el-dialog>
    </el-card>



  </div>
</template>
<script>
    import TableList from '../components/time'
    import my_stepbox from '@/components/StepBox/index'
    import { http_project_Detail } from '@/api/projectChanges'
    import {
        http_createObject_nodeType,
        http_createObject_userList,
        http_createObject_editProjectInit,
        http_createObject_saveAssign,
        http_createObject_getRole
    } from '@/api/createObject'
    import {Message} from "element-ui";
    export default {
        name: 'dayTask',
        data() {
            return {
                nodeId: "",
                // 节点周期列表
                nodeTypeList: [],
                // 节点点击
                nodeActive: 0,
                form: {
                    proTypeId: ''
                },
                // 周期时间
                zhouQiStart: ' ',
                zhouQiEnd: ' ',
                // 节点时间
                jieStart: ' ',
                jieEnd: ' ',
                dialogVisible: false,
                ruleForm: {
                    radio1: 3,
                    radio2: 3,
                    time1: '',
                    time2: '',
                    type: []
                },
                saveLoading: false,
                rules: {},
                tableRoleData: [],
                tableTimeList: [{
                    work: false,
                    workDate: '2020-10-01'
                }],
                selectOptions: [],
                addValue: [],
                // 流转项目负责人列表
                userList: [],
                userPageSize: 10,
                usertotal: 0,
                userPageCurrent: 0,
                userName: '',
                arr: [],
                detailInfo: {},
                tableUsers: [],
                centerDialogVisible: false,
            }
        },
        components: {my_stepbox, TableList},
        computed: {},
        mounted() {
            // this.getEditProjectInit()

            // this.getUserLsit()
            // this.getRoleList()
            this.init()
        },
        methods: {
            init() {
                this.getDetailInfo()
            },
            // 获取当前项目详情
            async getDetailInfo() {
                const params = {
                    id: this.$route.query.id
                }
                const res = await http_project_Detail(params)
                if (res.stateCode && res.stateCode === '0000') {
                    this.detailInfo = res.data
                    const proNodeList = this.detailInfo.proNodeList || []
                    const proAssignmentList = this.detailInfo.proAssignmentList || []
                    this.nodeActive = proNodeList.findIndex(el => !proAssignmentList.some(item => item.nodeId == el.proNodeId && item.inputHours)) || 0
                    this.exceNext()
                }
            },
            exceNext() {
                this.getEditProjectInit()
                this.getUserLsit()
                this.getRoleList()
            },
            // 获取数据
            getEditProjectInit() {
                http_createObject_editProjectInit({id: this.$route.query.id}).then((res) => {
                    if (res.success) {
                        // 项目类型Id
                        for (var p in res.data) {
                            this.form[p] = res.data[p]
                        }
                        sessionStorage.setItem('form', JSON.stringify(res.data))
                        // 暂时写死的 项目类型Id

                        this.form.proTypeId = this.form.proTypeId + ''
                        this.zhouQiStart = res.data.proStartDay
                        this.zhouQiEnd = res.data.proEndday
                        this.jieStart = res.data.proNodeList[this.nodeActive].startDate
                        this.jieEnd = res.data.proNodeList[this.nodeActive].endDate
                        this.tableTimeList = res.data.proNodeList[this.nodeActive].proDateInfoList
                        res.data.proNodeList.forEach((item, index) => {
                            res.data.proNodeList[index].proDateInfoList.forEach((itemA) => {
                                var string = itemA.workDate.replace('-', '.')
                                itemA.value = string.replace('-', '.')
                            })
                            this.nodeTypeList.push({
                                tableTimeList: res.data.proNodeList[index].proDateInfoList,
                                nodeId: res.data.proNodeList[index].proNodeId,
                                jieStart: res.data.proNodeList[index].startDate,
                                jieEnd: res.data.proNodeList[index].endDate
                            })


                        })
                        this.tableTimeList.forEach((item, index) => {
                            var string = item.workDate.replace('-', '.')
                            item.value = string.replace('-', '.')
                        })
                        this.getNodeType()
                    } else {
                        this.$message(res.message)
                    }
                })
            },
            // 根据类型获取项目初始节点
            getNodeType() {
                http_createObject_nodeType({typeId: this.form.proTypeId}).then((res) => {

                    if (res.success) {
                        this.$nextTick(() => {
                            this.nodeTypeList.forEach((item, index) => {
                                this.$set(item, 'nodeName', res.data[index].nodeName)
                            })
                        })

                        if (this.nodeTypeList.length) {
                            this.nodeId = this.nodeTypeList[0].nodeId
                        }
                    } else {
                        this.$message(res.message)
                    }
                })
            },
            isAssign(i){
                const nextNodeChangesArr = this.detailInfo.proAssignmentList && this.detailInfo.proAssignmentList.filter(el => el.nodeId == this.nodeTypeList[i].nodeId && el.inputHours) || []
                if (nextNodeChangesArr.length > 0) {
                    return true
                }
            },
            // 全部提交
            submitForm(formName) {
                var _this = this;
                var proAssignmentList = []
                var proPlanHoursList = []

                this.nodeTypeList.forEach((item, index) => {
                    var obj =  _this.$refs['tab' + index][0].submitForm()
                    proAssignmentList = [...proAssignmentList,...obj.proAssignmentList]
                    proPlanHoursList = [...proPlanHoursList,...obj.proPlanHoursList]

                })
                let sub = true
                if (proAssignmentList != null && proAssignmentList.length == 0){
                    Message.error("请添加成员")
                    sub = false
                    return ;
                }else{
                    let m = 0
                    proAssignmentList.forEach(p=>{
                        if (p.inputStart === null || p.inputEnd === null || p.inputHours === null || p.inputStart === '' || p.inputEnd === '' || p.inputHours === ''  ){
                            m++
                            sub = false
                        }
                    })
                    if (m>0){
                        Message.error(" 每个成员: 开始 / 结束 / 累计投入，都不可为空")
                        return ;
                    }
                }
                if (sub == true) {
                    var allObj = {
                        proAssignmentList,
                        proPlanHoursList
                    }
                    this.saveLoading = true
                    http_createObject_saveAssign(allObj).then((res) => {
                        if (res.success) {
                            this.$message({
                                message: '创建成功',
                                type: 'success'
                            })
                            this.centerDialogVisible = true
                            this.saveLoading = false
                            // this.$router.push('/dashboard')
                        } else {
                            this.$message(res.message)
                            this.saveLoading = false
                        }
                    })
                }

            },
            // 节点回调
            abc(val, item) {
                const nextNodeChangesArr = this.detailInfo.proAssignmentList && this.detailInfo.proAssignmentList.filter(el => el.nodeId == item.nodeId && el.inputHours) || []
                if (nextNodeChangesArr.length > 0) {
                    this.$message('该节点已经分配')
                    return
                }
                this.nodeActive = val
                this.nodeId = this.nodeTypeList[this.nodeActive].nodeId
                this.jieStart = this.form.proNodeList[this.nodeActive].startDate
                this.jieEnd = this.form.proNodeList[this.nodeActive].endDate
                this.tableTimeList = this.form.proNodeList[this.nodeActive].proDateInfoList
                this.tableTimeList.forEach((itemA, index) => {
                    var string = itemA.workDate.replace('-', '.')
                    itemA.value = string.replace('-', '.')
                })
            },
            // 时间框点击
            taskTimeChange(val) {
                val.all = 0
                this.tableTimeList.forEach((item, index) => {
                    if (new Date(val.start).getTime() <= new Date(item.workDate).getTime() && new Date(val.end).getTime() >= new Date(item.workDate).getTime()) {
                        if (item.work || !this.ruleForm.type[0]) {
                            if (Number(val[item.value])) {
                                val.all += Number(val[item.value])
                            }
                        }
                    }
                })
            },
            // all框点击
            taskAllChang(val) {
                if (val.mode) {
                    if (val.all > 0) {
                        var flag = 0
                        var timeList = []
                        this.tableTimeList.forEach((item, index) => {
                            if (new Date(val.start).getTime() <= new Date(item.workDate).getTime() && new Date(val.end).getTime() >= new Date(item.workDate).getTime()) {
                                if (item.work || !this.ruleForm.type[0]) {
                                    flag++
                                    var string = item.workDate.replace('-', '.')
                                    timeList.push(string.replace('-', '.'))
                                }
                            }
                        })
                        timeList.forEach((item, index) => {
                            val[item] = val.all / flag
                        })
                    }
                }
            },
            // 是否剔除节假日
            checkClick(val) {
                // 0 未选剔除节假日 1.。
                this.tableTimeList.forEach((item, index) => {
                    this.tableRoleData.some((it, ind) => {
                        if (!item.work && it[item.value]) {
                            if (val.length) {
                                it.all -= it[item.value]
                            } else {
                                it.all += it[item.value]
                            }
                        }
                    })
                })
            },
            // 投入方式选择
            typeClick(val) {
                Object.keys(val).forEach((item, index) => {
                    if (item != 'roleId' && item != 'role' && item != 'mode' && item != 'jueSe') {
                        val[item] = ''
                    }
                })
            },
            // 开始时间选择
            choseStart(value) {
                if (new Date(value.start) < new Date(this.jieStart).getTime()) {
                    this.$message('选择日期不在节点范围')
                    value.start = ''
                }
                if (new Date(value.start) > new Date(this.jieEnd).getTime()) {
                    this.$message('选择日期不在节点范围')
                    value.start = ''
                }

            },
            // 结束时间选择
            choseEnd(value) {
                if (new Date(value.end) > new Date(this.jieEnd).getTime()) {
                    this.$message('选择日期不在节点范围')
                    value.end = ''
                }
                if (new Date(value.end) < new Date(this.jieStart).getTime()) {
                    this.$message('选择日期不在节点范围')
                    value.end = ''
                }

            },
            // 人员表
            getUserLsit() {
                http_createObject_userList({
                    pageNum: this.userPageCurrent,
                    pageSize: this.userPageSize,
                    userName: this.userName
                }).then((res) => {
                    if (res.success) {
                        this.userList = res.data.records
                        this.usertotal = res.data.total
                        // 测试
                        // this.tableRoleData.push({
                        //   roleId : this.userList[1].userId,
                        //   role: this.userList[1].userName,
                        //   mode: true,
                        //   start: '',
                        //   end: '',
                        //   all: ''
                        // })
                        // this.tableRoleData.push({
                        //   roleId : this.userList[2].userId,
                        //   role: this.userList[2].userName,
                        //   mode: false,
                        //   start: '',
                        //   end: '',
                        //   all: ''
                        // })
                        if (this.usertotal) {
                            if (this.path) {
                                this.form.managerName = this.userList[0].userName
                                this.form.proManager = this.userList[0].userId
                            } else {
                                this.userList.forEach((item, index) => {
                                    if (this.form.proManager == item.userId) this.form.managerName = item.userName
                                })
                            }
                        }
                    } else {
                        this.$message(res.message)
                    }
                })
            },
            // 人员角色列表
            getRoleList() {
                http_createObject_getRole().then((res) => {
                    this.selectOptions = res.data
                })
            },
            // 添加角色
            addRole(val) {
                var flag
                if (this.tableRoleData.length) {
                    this.tableRoleData.some((item, index) => {
                        if (item.roleId == val.userId) {
                            this.$message('已添加该角色')
                            flag = true
                            return true
                        }
                    })
                }
                if (!flag) {
                    if (val.selectValue) {
                        this.tableRoleData.push({
                            jueSe: val.selectValue,
                            roleId: val.userId,
                            role: val.userName,
                            mode: true,
                            start: '',
                            end: '',
                            all: ''
                        })
                    } else {
                        this.$message('请选择项目角色再添加')
                    }

                }
            },
            handleSizeChange(val) {
                this.userPageCurrent = val
                this.getUserLsit()
            },
            handleCurrentChange(val) {
                this.userPageCurrent = val
                this.getUserLsit()
            },
            gotoReview(){
                let proId = this.$route.query.id
                this.$router.push("/review?proId="+proId)
            },

        }
    }
</script>

<style lang="scss" scoped>

  .notes {
    font-size: 12px;
    color: #888888;
    line-height: 30px;
    margin-bottom: 22px
  }


  .el-button + .el-button {
    margin-left: 0px;
  }
</style>
